package com.dgw.springbootmail.intercepter;

import com.dgw.springbootmail.listener.OnlinePersonListener;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.logging.Logger;

/**
 * @program: springboot-sendmail
 * @description:
 * @author: Mr.Dai
 * @create: 2020-02-29 22:28
 **/
@Component
public class myIntercepter implements HandlerInterceptor {

    private static final Logger LOGGER = Logger.getLogger(myIntercepter.class.getName());
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        LOGGER.info("preHandle 调用");
        request.setAttribute("starttime",System.currentTimeMillis());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        LOGGER.info("postHandle 调用");
        HttpSession session = request.getSession();
        String name = (String) session.getAttribute("name");
        if("dgw".equals(String.valueOf(name))){
            LOGGER.info("session 中存在 dgw");
            Cookie cookie = new Cookie("name","dgw");
            cookie.setMaxAge(24*1000);
            response.addCookie(cookie);
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        LOGGER.info("afterCompletion 调用");
        long starttime =(long) request.getAttribute("starttime");
        long endstime = System.currentTimeMillis();
        long s=endstime-starttime;
        LOGGER.info("请求耗时 "+s);
    }
}
